package com.youfan.service;

import com.alibaba.fastjson.JSONObject;
import com.youfan.config.RabbitMsgConvertConfigure;
import com.youfan.entity.YoufanOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SendMsgService implements RabbitTemplate.ReturnCallback, InitializingBean {
    Logger logger= LoggerFactory.getLogger(SendMsgService.class);
    // 此接口的默认实现是RabbitTemplate，目前只有一个实现，
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public SendMsgService(){

    }

    /**
     * 发送订单信息
     *
     * @param youfanOrder
     */
    public void sendOrderInfo(YoufanOrder youfanOrder) {

        CorrelationData correlationData = new CorrelationData();
        youfanOrder.setCount(1);
        correlationData.setId(JSONObject.toJSONString(youfanOrder));
        rabbitTemplate.convertAndSend(RabbitMsgConvertConfigure.SPRING_BOOT_EXCHANGE, RabbitMsgConvertConfigure.SPRING_BOOT_BIND_KEY,youfanOrder,correlationData);
    }

    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {
        logger.info(message.toString());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        rabbitTemplate.setReturnCallback(this);
        rabbitTemplate.setConfirmCallback(new MyConfirmCallback());
    }

    class MyConfirmCallback implements  RabbitTemplate.ConfirmCallback{

        /**
         * 确认提交，事务控制
         * @param correlationData
         * @param ack
         * @param cause
         */
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            String id = correlationData.getId();
            System.out.println(id);
            if (!ack) {
                //重试3次
                YoufanOrder youfanOrder = JSONObject.parseObject(id,YoufanOrder.class);
                int count = youfanOrder.getCount();
                if(count<=3) {
                    count++;
                    youfanOrder.setCount(count);
                    amqpTemplate.convertAndSend(RabbitMsgConvertConfigure.SPRING_BOOT_EXCHANGE, RabbitMsgConvertConfigure.SPRING_BOOT_BIND_KEY,youfanOrder );
                    System.out.println("youfanOrder 消息发送失败" + cause + correlationData.toString());
                }else{
                    //todo 记录到数据库中
                    System.out.println("");
                }
            } else {
                System.out.println("youfanOrder 消息发送成功 ");
            }
        }
    }
}
